package nl.twleaks.alice.tasks;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import static com.google.appengine.api.urlfetch.FetchOptions.Builder.*;

import nl.twleaks.alice.entities.User;
import nl.twleaks.alice.task.RequestTask;
import nl.twleaks.alice.task.Task;
import nl.twleaks.alice.task.TaskExecutor;

@SuppressWarnings("serial")
public class LoginTask extends RequestTask implements Task {
	
	Task task;
	
	public LoginTask(User user) {
		super(user);
		setWait(1000, 2500);
		task = new LoginSelectWorldTask(user);
	}

	@Override
	public void beforeExecute() {
		try {
			request = new HTTPRequest(new URL("http://www.tribalwars.nl/index.php?action=login&server_list=1&show_server_selection=1"), HTTPMethod.POST, doNotFollowRedirects());
			request.setPayload(new String("user=" + getUser().getUsername() + "&password=" + getUser().getPassword() + "&clear=true").getBytes());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterExecute() {
        String output = new String(response.getContent());
        if(output.indexOf("error") < 0) {
           HashMap<String, String> data = new HashMap<String, String>();
           Pattern regex = Pattern.compile("<input name=\\\\\\\"(.*?)\\\\\\\" type=\\\\\\\"hidden\\\\\\\" value=\\\\\\\"(.*?)\\\\\\\" \\\\/>", Pattern.DOTALL);
           Matcher matcher = regex.matcher(output);
           while (matcher.find()) {
               data.put(matcher.group(1), matcher.group(2));
           } 
           task.set("hash", data.get("password"));
       } else {
    	   System.out.println(output);
       }
	}
	
	@Override
	public void afterTask() {
		if(task.has("hash")) {
			TaskExecutor.execute(task);
		}
	}
}
